package queryfish.google.search;

import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import java.util.ArrayList;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class GoogleSearch {
	public static ArrayList<String> arrTitle = new ArrayList<String>();
	public static ArrayList<String> arrURL = new ArrayList<String>();

	public static void getSearch(String nameFish) throws IOException {

		String google = "http://www.google.com/search?q=";
		String search = "cá cảnh " + nameFish;
		String charset = "UTF-8";
		String userAgent = "ExampleBot 1.0 (+http://example.com/bot)"; // Change
																		// this
																		// to
																		// your
																		// company's
																		// name
																		// and
																		// bot
																		// homepage!

		Elements links = Jsoup
				.connect(google + URLEncoder.encode(search, charset))
				.userAgent(userAgent).get().select("li.g>h3>a");

		for (Element link : links) {
			String title = link.text();
			String url = link.absUrl("href"); // Google returns URLs in format
												// "http:/ /www.google.com/url?q=<url>&sa=U&ei=<someKey>".
			url = URLDecoder.decode(
					url.substring(url.indexOf('=') + 1, url.indexOf('&')),
					"UTF-8");

			if (!url.startsWith("http")) {
				continue; // Ads/news/etc.

			}
			arrTitle.add("Title : " + title);
			arrURL.add("URL : " + url);
		}
		// for (int i = 0; i < arrTitle.size(); i++) {
		// System.out.println("Title: " + arrTitle.get(i));
		// System.out.println("URL: " + arrURL.get(i));
		// }
	}

}
